package com.itelite.controller;

import com.github.pagehelper.PageInfo;
import com.itelite.common.info.Result;
import com.itelite.common.util.SecurityUtils;
import com.itelite.domain.dto.TeacherParam;
import com.itelite.domain.pojo.Teacher;
import com.itelite.handler.ValidateHandler;
import com.itelite.service.TeacherService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 沈洋 邮箱:1845973183@qq.com
 * @create 2021/8/8-20:57
 **/
@Api("老师模块")
@Slf4j
@RestController
@RequestMapping("/teacher/api")
public class TeacherController {
    @Autowired
    private TeacherService teacherService;

    @ApiOperation("获取老师名单")
    @GetMapping("/teacher")
    public Result getTeachers(){
        return Result.success().data("teachers",teacherService.getTeachers());
    }
    @ApiOperation("获取老师名单(查询)")
    @PostMapping("/queryTeacher")
    public Result queryTeachers(@Validated @RequestBody(required = true) TeacherParam param, BindingResult error){
        if (error.hasErrors()) {
            return Result.failure(ValidateHandler.catchErrors(error));
        }
        PageInfo<Teacher> teachers = teacherService.getTeachers(param);
        return Result.success().data("teachers",teachers);
    }

    @ApiOperation("添加老师")
    @PostMapping("/addTeacher")
    public Result addTeacher(@RequestBody@Validated Teacher teacher,BindingResult error){
        if(error.hasErrors()) return Result.failure(ValidateHandler.catchErrors(error));
        Result result = null;
        if (teacherService.addTeacher(teacher)) {
            log.info("操作： {} | 操作者：{}","添加老师-"+teacher.getTeacherName(), SecurityUtils.getRealName());
            result = Result.success();
        }else {
            result = Result.failure();
        }
        return result;
    }

    @ApiOperation("删除老师")
    @GetMapping("/deleteTeacher/{teacherId}")
    @PreAuthorize("hasAnyRole('ADMIN')")
    public Result deleteTeacher(@PathVariable Integer teacherId){
        if (teacherService.deleteTeacher(teacherId)) {
            log.info("操作： {} | 操作者：{}","删除老师"+teacherId,SecurityUtils.getRealName());
            return Result.success();
        }return Result.failure();
    }

}
